package com.adan.auditlog.service;

import com.adan.auditlog.mapper.AuditLogEntityMapper;
import com.alibaba.fastjson.JSON;
import com.adan.auditlog.config.AuditLogContext;
import com.adan.auditlog.AuthUtil;
import com.adan.auditlog.entity.DBOperationLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class IOperationLogServiceImpl implements IOperationLogService {
	@Autowired
	private AuditLogEntityMapper mapper;
	@Autowired
	private AuditLogContext auditLogContext;

	@Override
	public void insert(DBOperationLog opLog) {
		if (log.isDebugEnabled()) {
			log.debug("【日志审计】" + JSON.toJSONString(opLog));
		}
		try {
			mapper.insert(opLog);
		} catch (Exception ex) {
			log.error("", ex);
		}
	}

	@Override
	public void addAuditLog(String tableName, String bizId, String changeValue, String remark) {
		DBOperationLog.DBOperationLogBuilder logBuilder = DBOperationLog.builder();
		logBuilder.tableName(tableName);
		logBuilder.bizId(bizId);
		logBuilder.changeValue(changeValue);
		logBuilder.createTime(new Date());
		logBuilder.remark(remark);
		if (AuthUtil.getAccount() != null) {
			logBuilder.userId(String.valueOf(AuthUtil.getAccount().getAccountId()));
			logBuilder.userName(String.valueOf(AuthUtil.getAccount().getName()));
		}
		if (auditLogContext != null && auditLogContext.getAuditLogParam() != null) {
			logBuilder.traceId(MDC.get("traceId"));
			if (StringUtils.isBlank(remark)) {
				logBuilder.remark(auditLogContext.getAuditLogParam().getRemark());
			}
			logBuilder.methodName(auditLogContext.getAuditLogParam().getMethodName());
		}
		this.insert(logBuilder.build());
	}

	@Override
	public void addAuditLog(String tableName, String bizId, String changeValue) {
		addAuditLog(tableName, bizId, changeValue, null);
	}
}
